// pages/Plan/PlanPage.jsx
import { Customer, CustomerCards, Plans } from "api/queries";
import Box from "components/atoms/Box";
import Loader from "components/atoms/Loader";
import { isAccountActive, isFreeTrial } from "libs/utils";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useQuery } from "react-query";
import { useNavigate } from "react-router-dom";
import { Elements } from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';
import { useAuth } from 'contexts/AuthContext';
import PlanCard from "./PlanCard";
import QueryDebugLogger from 'components/debugging/QueryDebugLogger';
import {
  Grid,
  Typography,
  Button,
  ButtonGroup,
  Container,
  Alert,
  AlertTitle,
  useTheme
} from '@mui/material';
import { styled } from '@mui/material/styles';

// Styled components with cyberpunk aesthetic
const CyberContainer = styled(Container)(({ theme }) => ({
  padding: theme.spacing(4),
  position: 'relative',
  '&::before': {
    content: '""',
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    height: '2px',
    background: 'linear-gradient(90deg, transparent, #00fff2, transparent)',
    animation: 'scanline 8s linear infinite',
  },
  '@keyframes scanline': {
    '0%': { transform: 'translateX(-100%)' },
    '100%': { transform: 'translateX(100%)' }
  }
}));

const PageHeader = styled(Typography)(({ theme }) => ({
  fontFamily: '"Rajdhani", "Poppins", sans-serif',
  fontSize: '3.5rem',
  fontWeight: '700',
  textAlign: 'center',
  letterSpacing: '0.15em',
  color: theme.palette.mode === 'dark' ? '#ffffff' : '#000000',
  textShadow: theme.palette.mode === 'dark' 
    ? '0 0 10px rgba(0, 255, 242, 0.7), 0 0 20px rgba(0, 255, 242, 0.4)' 
    : '0 0 5px rgba(0, 0, 0, 0.3)',
  margin: theme.spacing(2, 0, 4),
  [theme.breakpoints.down('sm')]: {
    fontSize: '2.5rem',
  },
}));

const SubHeader = styled(Typography)(({ theme }) => ({
  fontFamily: '"Rajdhani", "Poppins", sans-serif',
  fontSize: '1.5rem',
  textAlign: 'center',
  marginBottom: theme.spacing(6),
  color: theme.palette.mode === 'dark' ? 'rgba(255, 255, 255, 0.7)' : 'rgba(0, 0, 0, 0.7)',
  [theme.breakpoints.down('sm')]: {
    fontSize: '1.2rem',
  },
}));

const WarningBox = styled(Box)(({ theme }) => ({
  padding: theme.spacing(3),
  borderRadius: '12px',
  border: `1px solid ${theme.palette.warning.main}`,
  background: theme.palette.mode === 'dark'
    ? 'linear-gradient(145deg, rgba(255, 152, 0, 0.05), rgba(255, 152, 0, 0.02))'
    : 'linear-gradient(145deg, rgba(255, 152, 0, 0.1), rgba(255, 152, 0, 0.05))',
  boxShadow: theme.palette.mode === 'dark'
    ? 'inset 1px 1px 2px rgba(0, 0, 0, 0.2), inset -1px -1px 2px rgba(255, 255, 255, 0.05), 0 0 15px rgba(255, 152, 0, 0.2)'
    : 'inset 1px 1px 3px rgba(223, 227, 238, 0.5), inset -1px -1px 3px rgba(255, 255, 255, 0.8), 0 0 10px rgba(255, 152, 0, 0.1)',
}));

const WarningTitle = styled(Typography)(({ theme }) => ({
  fontFamily: '"Rajdhani", "Poppins", sans-serif',
  fontSize: '1.8rem',
  fontWeight: '600',
  color: theme.palette.warning.main,
  marginBottom: theme.spacing(2),
}));

const CyberButtonGroup = styled(ButtonGroup)(({ theme }) => ({
  borderRadius: '12px',
  boxShadow: theme.palette.mode === 'dark'
    ? '5px 5px 10px rgba(0, 0, 0, 0.5), -5px -5px 10px rgba(30, 30, 30, 0.3)'
    : '5px 5px 10px rgba(200, 200, 200, 0.3), -5px -5px 10px rgba(255, 255, 255, 0.8)',
  padding: '2px',
  marginBottom: theme.spacing(4),
}));

const CyberButton = styled(Button)(({ theme, active }) => ({
  background: active
    ? theme.palette.mode === 'dark'
      ? 'linear-gradient(45deg, rgba(0, 255, 242, 0.2), rgba(0, 255, 242, 0.1))'
      : 'linear-gradient(45deg, rgba(0, 255, 242, 0.4), rgba(0, 255, 242, 0.2))'
    : theme.palette.mode === 'dark'
      ? 'linear-gradient(145deg, rgba(255, 255, 255, 0.05), rgba(255, 255, 255, 0.02))'
      : 'linear-gradient(145deg, rgba(255, 255, 255, 0.9), rgba(223, 227, 238, 0.6))',
  color: active 
    ? '#00fff2' 
    : theme.palette.mode === 'dark' ? '#ffffff' : '#000000',
  textShadow: active 
    ? '0 0 8px #00fff2' 
    : 'none',
  fontFamily: '"Rajdhani", "Poppins", sans-serif',
  fontSize: '1.3rem',
  fontWeight: '600',
  padding: theme.spacing(1.5, 3),
  textTransform: 'none',
  letterSpacing: '0.05em',
  transition: 'all 0.3s ease',
  '&:hover': {
    color: '#00fff2',
    textShadow: '0 0 8px #00fff2',
    background: theme.palette.mode === 'dark'
      ? 'linear-gradient(135deg, rgba(0, 255, 242, 0.2), rgba(0, 255, 242, 0.1))'
      : 'linear-gradient(135deg, rgba(0, 255, 242, 0.4), rgba(0, 255, 242, 0.2))',
  },
}));

const CyberLoadingBox = styled(Box)(({ theme }) => ({
  background: theme.palette.mode === 'dark'
    ? 'linear-gradient(145deg, rgba(0, 0, 0, 0.9), rgba(20, 20, 20, 0.8))'
    : 'linear-gradient(145deg, rgba(255, 255, 255, 0.9), rgba(240, 240, 240, 0.8))',
  borderRadius: '12px',
  padding: theme.spacing(5),
  textAlign: 'center',
  boxShadow: theme.palette.mode === 'dark'
    ? '5px 5px 10px rgba(0, 0, 0, 0.5), -5px -5px 10px rgba(30, 30, 30, 0.3)'
    : '5px 5px 10px rgba(200, 200, 200, 0.3), -5px -5px 10px rgba(255, 255, 255, 0.8)',
}));

const PlanPage = () => {
  const { user } = useAuth();
  const { t } = useTranslation();
  const navigate = useNavigate();
  const theme = useTheme();
  //const isMobile = useMediaQuery(theme.breakpoints.down('sm'));
  const [selectedPlanRecurring, setSelectedPlanRecurring] = useState(1);
  const [selectedPlan, setSelectedPlan] = useState(undefined);
  const [currentSubscription, setCurrentSubscription] = useState();
  const [stripePromise, setStripePromise] = useState(null);

  // Navigate when a plan is selected
  useEffect(() => {
    if (selectedPlan !== undefined) {
      navigate(`/plan/${selectedPlan}/subscribe`);
    }
  }, [selectedPlan, navigate]);

  // Customer query - renamed for consistency
  const customerQuery = useQuery("Customer", Customer, {
    retry: false,
    onSuccess: (data) => {
      if (!isFreeTrial(user.account)) {
        try {
          const cs = data?.data?.subscriptions?.data?.[0];
          if (cs) {
            setCurrentSubscription(cs);
          }
        } catch (e) {
          console.error("Error processing subscription:", e);
        }
      }
    },
  });

  // Plans query
  const plansQuery = useQuery(
    "Plans",
    Plans,
    {
      retry: false,
      onSuccess: (data) => {
        // Initialize Stripe with the public key when plans data is loaded
        if (data?.data?.publicKey) {
          setStripePromise(loadStripe(data.data.publicKey));
        }
      },
    }
  );

  // Cards query
  const cardsQuery = useQuery(
    ["CustomerCards", user.accountId],
    CustomerCards,
    {
      retry: false,
    }
  );

  // Prepare queries for debug logger
  const queriesForDebug = [
    {
      name: "Customer Query",
      isLoading: customerQuery.isLoading,
      isError: customerQuery.isError,
      error: customerQuery.error,
      data: customerQuery.data
    },
    {
      name: "Plans Query",
      isLoading: plansQuery.isLoading,
      isError: plansQuery.isError,
      error: plansQuery.error,
      data: plansQuery.data
    },
    {
      name: "Cards Query",
      isLoading: cardsQuery.isLoading,
      isError: cardsQuery.isError,
      error: cardsQuery.error,
      data: cardsQuery.data
    },
    {
      name: "State Variables",
      isLoading: false,
      isError: false,
      data: {
        selectedPlanRecurring,
        selectedPlan,
        currentSubscription,
        stripePromise: stripePromise ? "Loaded" : "Not Loaded"
      }
    }
  ];

  // Loading state
  if (customerQuery.isLoading || plansQuery.isLoading || cardsQuery.isLoading) {
    return (
      <>
        <CyberLoadingBox>
          <Loader />
        </CyberLoadingBox>
        <QueryDebugLogger queries={queriesForDebug} isVisible={false} />
      </>
    );
  }

  // Error handling
  if (customerQuery.isError || plansQuery.isError || cardsQuery.isError) {
    return (
      <CyberContainer maxWidth="md">
        <Alert severity="error" sx={{ 
          mt: 3, 
          borderRadius: '12px',
          padding: '16px',
          background: theme.palette.mode === 'dark'
            ? 'linear-gradient(145deg, rgba(220, 0, 0, 0.1), rgba(220, 0, 0, 0.05))'
            : 'linear-gradient(145deg, rgba(255, 240, 240, 0.9), rgba(255, 220, 220, 0.6))',
          border: '1px solid',
          borderColor: 'error.main',
          boxShadow: theme.palette.mode === 'dark'
            ? 'inset 1px 1px 2px rgba(0, 0, 0, 0.2), inset -1px -1px 2px rgba(255, 255, 255, 0.05), 0 0 15px rgba(220, 0, 0, 0.2)'
            : 'inset 1px 1px 3px rgba(255, 200, 200, 0.5), inset -1px -1px 3px rgba(255, 255, 255, 0.8), 0 0 10px rgba(220, 0, 0, 0.1)',
        }}>
          <AlertTitle sx={{ 
            fontFamily: '"Rajdhani", "Poppins", sans-serif',
            fontSize: '1.8rem',
            fontWeight: '600',
          }}>
            {t("common.error")}
          </AlertTitle>
          <Typography variant="body1" sx={{ 
            fontFamily: '"Rajdhani", "Poppins", sans-serif',
            fontSize: '1.2rem' 
          }}>
            {t("planPage.errorLoadingData")}
          </Typography>
        </Alert>
        <QueryDebugLogger queries={queriesForDebug} isVisible={true} />
      </CyberContainer>
    );
  }

  // Check if plans data is available - FIXED: More explicit check
  if (!plansQuery.data || !plansQuery.data.data || !plansQuery.data.data.plans) {
    return (
      <CyberContainer maxWidth="md">
        <Grid container spacing={3} sx={{ mt: 3 }}>
          <Grid item xs={12}>
            <WarningBox>
              <WarningTitle>
                {t("planPage.planDataNotAvailable")}
              </WarningTitle>
              <Typography variant="body1" paragraph sx={{ 
                fontFamily: '"Rajdhani", "Poppins", sans-serif',
                fontSize: '1.2rem' 
              }}>
                {t("planPage.planDataCouldNotBeLoaded")}
              </Typography>
              <ul>
                <li>
                  <Typography sx={{ 
                    fontFamily: '"Rajdhani", "Poppins", sans-serif',
                    fontSize: '1.1rem' 
                  }}>
                    {t("planPage.plansAPIRequestFailed")}
                  </Typography>
                </li>
                <li>
                  <Typography sx={{ 
                    fontFamily: '"Rajdhani", "Poppins", sans-serif',
                    fontSize: '1.1rem' 
                  }}>
                    {t("planPage.noPlansReturned")}
                  </Typography>
                </li>
                <li>
                  <Typography sx={{ 
                    fontFamily: '"Rajdhani", "Poppins", sans-serif',
                    fontSize: '1.1rem' 
                  }}>
                    {t("planPage.planDataStructureChanged")}
                  </Typography>
                </li>
              </ul>
              <CyberButton 
                variant="contained" 
                sx={{ mt: 2 }}
                onClick={() => window.location.reload()}
              >
                {t("common.refresh")}
              </CyberButton>
            </WarningBox>
          </Grid>
        </Grid>
        <QueryDebugLogger queries={queriesForDebug} isVisible={false} />
      </CyberContainer>
    );
  }

  // Filter plans by billing interval
  const monthlyPlans = plansQuery.data.data.plans.filter(p => p.monthly) || [];
  const yearlyPlans = plansQuery.data.data.plans.filter(p => !p.monthly) || [];
  const showRecurringToggle = monthlyPlans.length > 0 && yearlyPlans.length > 0;

  // If no plans match the selected interval
  const noPlansToShow = 
    (selectedPlanRecurring === 1 && monthlyPlans.length === 0) || 
    (selectedPlanRecurring === 2 && yearlyPlans.length === 0);

  if (noPlansToShow) {
    return (
      <CyberContainer maxWidth="md">
        <Grid container spacing={3} sx={{ mt: 3 }}>
          <Grid item xs={12}>
            <WarningBox>
              <WarningTitle>
                {t("planPage.noPlansAvailable")}
              </WarningTitle>
              <Typography variant="body1" paragraph sx={{ 
                fontFamily: '"Rajdhani", "Poppins", sans-serif',
                fontSize: '1.2rem' 
              }}>
                {selectedPlanRecurring === 1 
                  ? t("planPage.noMonthlyPlansAvailable") 
                  : t("planPage.noYearlyPlansAvailable")}
              </Typography>
              {showRecurringToggle && (
                <CyberButton 
                  variant="contained" 
                  sx={{ mt: 2 }}
                  onClick={() => setSelectedPlanRecurring(selectedPlanRecurring === 1 ? 2 : 1)}
                >
                  {selectedPlanRecurring === 1 
                    ? t("planPage.switchToYearly") 
                    : t("planPage.switchToMonthly")}
                </CyberButton>
              )}
            </WarningBox>
          </Grid>
        </Grid>
        <QueryDebugLogger queries={queriesForDebug} isVisible={false} />
      </CyberContainer>
    );
  }

  // Stripe Elements options
  const options = {
    fonts: [
      {
        cssSrc: 'https://fonts.googleapis.com/css?family=Rajdhani:400,600,700|Roboto',
      },
    ],
  };

  return (
    <>
      <CyberContainer>
        <PageHeader component="h1">
          {t("planPage.selectaPlan")}
        </PageHeader>
        
        {!isAccountActive(user.account) && (
          <SubHeader>
            {t("planPage.deactivatedAccountNotice")}
          </SubHeader>
        )}
        
        {stripePromise ? (
          <Elements stripe={stripePromise} options={options}>
            <Grid container direction="column" spacing={3}>
              {showRecurringToggle && (
                <Grid item>
                  <CyberButtonGroup fullWidth>
                    <CyberButton
                      onClick={() => setSelectedPlanRecurring(1)}
                      active={selectedPlanRecurring === 1}
                    >
                      {t("planPage.monthly")}
                    </CyberButton>
                    <CyberButton
                      onClick={() => setSelectedPlanRecurring(2)}
                      active={selectedPlanRecurring === 2}
                    >
                      {t("planPage.yearly")}
                    </CyberButton>
                  </CyberButtonGroup>
                </Grid>
              )}

              <Grid item>
                <Grid container spacing={3}>
                  {selectedPlanRecurring === 1 && monthlyPlans.map((plan, i) => (
                    <Grid item xs={12} md={4} key={`monthly-${i}`}>
                      <PlanCard
                        plan={plan}
                        monthly
                        setSelectedPlan={setSelectedPlan}
                        currentSubscription={currentSubscription}
                        cardsData={cardsQuery.data?.data}
                      />
                    </Grid>
                  ))}

                  {selectedPlanRecurring === 2 && yearlyPlans.map((plan, i) => (
                    <Grid item xs={12} md={4} key={`yearly-${i}`}>
                      <PlanCard
                        plan={plan}
                        monthly={false}
                        setSelectedPlan={setSelectedPlan}
                        currentSubscription={currentSubscription}
                        cardsData={cardsQuery.data?.data}
                      />
                    </Grid>
                  ))}
                </Grid>
              </Grid>
            </Grid>
          </Elements>
        ) : (
          <CyberLoadingBox>
            <Loader />
          </CyberLoadingBox>
        )}
      </CyberContainer>
      <QueryDebugLogger queries={queriesForDebug} isVisible={false} />
    </>
  );
};

export default PlanPage;